package com.mrjoew.weekend.filters;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.mrjoew.utils.IPUtil;
import com.mrjoew.utils.RequestUtil;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author Christopher Jones
 * @desc 拦截所有 GET 请求
 * @since 2020/12/12 0012 22:53
 */
@Component
@Order(1)
public class AnyRequestFilter implements Filter {

    private final KafkaTemplate<String, Object> kafkaTemplate;

    public AnyRequestFilter(KafkaTemplate<String, Object> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        if (HttpMethod.GET.name().equals(httpServletRequest.getMethod())) {
            Map<String, Object> message = Maps.newHashMap();
            message.put("ip", IPUtil.ipToLong(RequestUtil.getIpAddress(httpServletRequest)));
            message.put("uri", httpServletRequest.getRequestURI());
            message.put("time", LocalDateTime.now());
            kafkaTemplate.send("requests", JSON.toJSONString(message));
        }
        chain.doFilter(request, response);
    }
}
